import { getChatStream, postChatQuery, postChatVllmQuery } from "@/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useState } from "react";
import { useSelector } from "react-redux";
import { RootStateI, UserI } from "@/types/system";
import { baseUrl } from "@/api/http_class";
import { ChatRequestI, MessageI } from "@/types/chat";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";

function HtmlRender({ html }: { html: string }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

const ChatInterfaceStream = () => {
  const content = `
  <div class="text-lg text-gray-800">参考资料搜索完成</div>
  我们知识库中找到<strong class="text-red-500">2</strong>种品规：
  <ol class="pl-5 list-decimal">
    <li class="mb-2">
      <a href="http://10.2.2.89/7257679834057277440/def" class="text-blue-500 underline">优思明(屈螺酮炔雌醇片)</a> &nbsp;&nbsp; 3mg:0.03mg x21片/盒 &nbsp;&nbsp;  德国Bayer Weimar GmbH & Co.KG(拜耳医药保健有限公司广州分公司分装)
    </li>
    <li class="mb-2">
      <a href="http://10.2.2.89/7257679834053083136/def" class="text-blue-500 underline">优思明(屈螺酮炔雌醇片)</a> &nbsp;&nbsp;  3mg: 0.3mg /片 &nbsp;&nbsp;  德国Bayer Weimar GmbH & Co.KG(拜耳医药保健有限公司广州分公司分装)
    </li>
  </ol>
  <div class="italic">优思明是一种口服避孕药，专门用于治疗乳腺癌。</div>
`;
  const [messages, setMessages] = useState<
    Array<{
      role: "user" | "assistant";
      content: string;
    }>
  >([
    { role: "user", content: "优思明是治疗什么病的？" },
    { role: "assistant", content: content },
  ]);
  const [streamMessages, setStreamMessages] = useState<string[]>([]);
  const [model, setModel] = useState("general");
  const [input, setInput] = useState("优思明是治疗什么病的？");
  const user: UserI = useSelector((state: RootStateI) => state.user);

  function uploadFiles() {
    const fileInput = document.getElementById(
      "fileInput"
    ) as HTMLInputElement | null;
    if (!fileInput || !fileInput.files) return;

    const formData = new FormData();

    for (let i = 0; i < fileInput.files.length; i++) {
      formData.append("files", fileInput.files[i]);
    }

    fetch("/api/upload", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("上传成功:", data);
      })
      .catch((error) => {
        console.error("上传失败:", error);
      });
  }

  const onChat = async () => {
    if (!input.trim()) return;
    // 深度拷贝messages
    let messagesCopy: MessageI[] = JSON.parse(JSON.stringify(messages));
    messagesCopy.push({
      role: "user",
      content: input,
      status: "pending",
      timestamp: Date.now(),
    });

    let data: ChatRequestI = {
      model: model,
      max_length: 10000,
      messages: messagesCopy,
    };

    postChatQuery(data).then(
      (res: any) => {
        console.log(res);
        // messagesCopy.push({
        //   role: "assistant",
        //   content: res.data,
        // });
        setMessages(messagesCopy);
        setInput("");
        // 继续获取流式输入结果
        // EventSource 是浏览器原生支持的流式传输协议，可以用于接收服务器推送的消息
        // EventSource发送Post请求，请求体为json，请求体为{text: input}

        // 将access_token添加到请求头中
        // `http://localhost:8001/api/v1/chat_vllm/stream?access_token=${user.accessToken}`
        const eventSource = new EventSource(
          // `${baseUrl}chat_transformer/stream?access_token=${user.accessToken}`
          `${baseUrl}chat_vllm/stream?access_token=${user.accessToken}`
        );

        eventSource.onmessage = (event) => {
          if (event.data === "[DONE]") {
            eventSource.close();
          } else {
            // 读取流式输出内容，并添加到messagesCopy中
            console.log(event.data);
            setStreamMessages((prev) => [...prev, event.data]);
            // 取出messagesCopy的最后一个元素
            // 如果lastMessage的role为assistant，则将event.data添加到lastMessage的content后面
            if (messagesCopy[messagesCopy.length - 1].role === "assistant") {
              messagesCopy[messagesCopy.length - 1].content += event.data;
            } else {
              messagesCopy.push({
                role: "assistant",
                content: event.data,
                status: "complete",
                timestamp: Date.now(),
              });
            }
            console.log(messagesCopy);
            // 设置messagesCopy
            setMessages(messagesCopy);
            setInput("");
          }
        };

        eventSource.onerror = (error) => {
          console.error("EventSource failed:", error);
          eventSource.close();
        };

        return () => {
          eventSource.close();
        };
      },
      (err: any) => {
        console.error(err);
      }
    );
  };

  return (
    <div className="flex h-screen flex-col">
      {/* 头部 */}
      <header className="border-b p-4">
        <h1 className="text-xl font-semibold">药学咨询</h1>
        {/* 下拉框选择模型 */}
        <select
          className="mt-2 ml-4"
          onChange={(e) => setModel(e.target.value)}
        >
          <option value="general">通用模型</option>
          <option value="medicine">药学模型</option>
        </select>
      </header>
      {/* 聊天区域 */}
      <ScrollArea className="flex-1 p-4">
        <div className="space-y-4">
          {messages.map((message, i) => (
            <div
              key={i}
              className={`flex ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
            >
              <div
                className={`rounded-lg p-4 max-w-[80%] ${
                  message.role === "user"
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted"
                }`}
              >
                <HtmlRender html={message.content} />
              </div>
            </div>
          ))}
        </div>
      </ScrollArea>
      {/* 输入区域 */}
      <div className="border-t p-4">
        <div className="flex gap-2">
          <Input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="输入您的问题..."
            className="flex-1"
          />
          {/* {streamMessages.join("")} */}
          <Button onClick={onChat}>发送</Button>
        </div>
      </div>
    </div>
  );
};

export default ChatInterfaceStream;
